package com.tarena.lbs.activity.rpc;

import com.tarena.lbs.activity.api.ActivityApi;
import com.tarena.lbs.activity.api.pojo.ActivityDto;
import com.tarena.lbs.activity.pojo.vo.ActivityVO;
import com.tarena.lbs.activity.service.ActivityService;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.utils.ListMatchUtils;
import com.tarena.lbs.user.api.UserApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;


@Slf4j
@Component
@DubboService
public class ActivityApiImpl implements ActivityApi {

    @DubboReference
    private UserApi userApi;

    @Autowired
    private ActivityService activityService;

    @Override
    public Boolean activityVisible(Integer userId, Integer activityId) throws BusinessException {
        //校验活动是否存在
        ActivityVO activityDto = activityService.detail(activityId);
        log.debug("activityDto:{}", activityDto);
        Asserts.isTrue(activityDto == null, new BusinessException("-4", "活动不存在"));
        //检验活动目标人群是否为空
        if(activityDto.getTargetCustomer() == null || activityDto.getTargetCustomer().isEmpty()){
            return true;
        }
        //调用UserApi查询用户所属人群
        List<Integer> groupIds = userApi.getUserGroupIds(userId,activityDto.getBusinessId());
        //判断活动目标人群是否再所属人群范围
        String targetCustomer = activityDto.getTargetCustomer();
        log.debug("活动人群:{}",targetCustomer);
        List<Integer> targetList = Arrays.asList(targetCustomer.split(",")).stream().map(Integer::parseInt).collect(java.util.stream.Collectors.toList());
        log.debug("用户人群列表:{}",groupIds);
        log.debug("活动目标人群:{}",targetList);
        return ListMatchUtils.hasAnyMatch(groupIds, targetList);
    }

    @Override
    public ActivityDto getActivityById(Integer activityId) {
        ActivityVO activityVO = activityService.detail(activityId);
        log.debug("activityVO:{}", activityVO);
        ActivityDto activityDto = new ActivityDto();
        BeanUtils.copyProperties(activityVO,activityDto);
        return activityDto;
    }
}
